//
//  XYProgressHUD.m
//  XYCustomAlertView
//
//  Created by gao chenyang on 2019/11/1.
//  Copyright © 2019 gao chenyang. All rights reserved.
//

#import "XYProgressHUD.h"
#import <tgmath.h>
#import "UIColor+XYColor.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#define XY_TEXTSIZE(text, font) [text length] > 0 ? [text \
sizeWithAttributes:@{NSFontAttributeName:font}] : CGSizeZero;
#else
#define XY_TEXTSIZE(text, font) [text length] > 0 ? [text sizeWithFont:font] : CGSizeZero;
#endif


#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#define XY_MULTILINE_TEXTSIZE(text, font, maxSize, mode) [text length] > 0 ? [text \
boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin) \
attributes:@{NSFontAttributeName:font} context:nil].size : CGSizeZero;
#else
#define XY_MULTILINE_TEXTSIZE(text, font, maxSize, mode) [text length] > 0 ? [text \
sizeWithFont:font constrainedToSize:maxSize lineBreakMode:mode] : CGSizeZero;
#endif

static const CGFloat kPadding = 10.f;
static const CGFloat kLabelFontSize = 16.f;
static const CGFloat kDetailsLabelFontSize = 12.f;
@interface XYProgressHUD()
{
    BOOL useAnimation;
    SEL methodForExecution;
    id targetForExecution;
    id objectForExecution;
    BOOL isFinished;
    CGAffineTransform rotationTransform;
}

@property (nonatomic, strong) UILabel * titleLabel;
@property (nonatomic, strong) UILabel * detailLabel;

@property (nonatomic, strong) UIView *indicator;

@property (nonatomic, strong) NSTimer *graceTimer;
@property (nonatomic, strong) NSTimer *minShowTimer;

@property (nonatomic, strong) NSDate *showStarted;
@property (nonatomic, assign, readwrite) CGSize size;
@end
@implementation XYProgressHUD
#pragma mark- public class methods
+ (XY_INSTANCETYPE)showHUDAddedTo:(UIView *)view animated:(BOOL)animated{
    XYProgressHUD *hud = [[self alloc] initWithView:view];
    hud.removeFromSuperViewOnHide = YES;
    [view addSubview:hud];
    [hud show:animated];
    return hud;
}

+ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated{
    XYProgressHUD *hud = [self HUDForView:view];
    if (hud != nil) {
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:animated];
        return YES;
    }
    return NO;
}

+ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated {
    NSArray *huds = [XYProgressHUD allHUDsForView:view];
    for (XYProgressHUD *hud in huds) {
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:animated];
    }
    return [huds count];
}

+ (XY_INSTANCETYPE)HUDForView:(UIView *)view {
    NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator];
    for (UIView *subview in subviewsEnum) {
        if ([subview isKindOfClass:self]) {
            return (XYProgressHUD *)subview;
        }
    }
    return nil;
}

//返回父视图对应的所有HUD视图
+ (NSArray *)allHUDsForView:(UIView *)view {
    NSMutableArray *huds = [NSMutableArray array];
    NSArray *subviews = view.subviews;
    for (UIView *aView in subviews) {
        if ([aView isKindOfClass:self]) {
            [huds addObject:aView];
        }
    }
    return [NSArray arrayWithArray:huds];
}
#pragma mark - Threading

- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated {
    methodForExecution = method;
    targetForExecution = target;
    objectForExecution = object;
    // Launch execution in new thread
    self.taskInProgress = YES;
    [NSThread detachNewThreadSelector:@selector(launchExecution) toTarget:self withObject:nil];
    // Show HUD view
    [self show:animated];
}

#if NS_BLOCKS_AVAILABLE

- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:nil];
}

- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(void (^)(void))completion {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:completion];
}

- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue {
    [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:nil];
}

- (void)showAnimated:(BOOL)animated
 whileExecutingBlock:(dispatch_block_t)block
             onQueue:(dispatch_queue_t)queue
     completionBlock:(nullable XYProgressHUDCompletionBlock)completion {
    self.taskInProgress = YES;
    self.completionBlock = completion;
    dispatch_async(queue, ^(void) {
        block();
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [self cleanUp];
        });
    });
    [self show:animated];
}

#endif
- (void)cleanUp {
    self.taskInProgress = NO;
    targetForExecution = nil;
    objectForExecution = nil;
    [self hide:useAnimation];
}
- (void)launchExecution {
    @autoreleasepool {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        // Start executing the requested task
        [targetForExecution performSelector:methodForExecution withObject:objectForExecution];
#pragma clang diagnostic pop
        // Task completed, update view in main thread (note: view operations should
        // be done only in the main thread)
        [self performSelectorOnMainThread:@selector(cleanUp) withObject:nil waitUntilDone:NO];
    }
}
#pragma mark - Lifecycle
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self _initDefaultValues];
        [self _setupLabels];
        [self _updateIndicators];
        
        [self _registerForKVO];
        [self _registerForNotifications];
    }
    return self;
}

- (id)initWithView:(UIView *)view {
//    NSAssert(view, @"View must not be nil.");
    if (view) {
        return [self initWithFrame:view.bounds];
    }else{
        return [self initWithFrame:CGRectZero];
    }
}

- (id)initWithWindow:(UIWindow *)window {
    return [self initWithView:window];
}

- (void)dealloc {
    [self _unregisterFromNotifications];
    [self _unregisterFromKVO];
}
#pragma mark - Layout

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // Entirely cover the parent view
    UIView *parent = self.superview;
    if (self.isBlockUI) {
        self.frame = parent.bounds;
    }
    CGRect bounds = parent.bounds;
    
    // Determine the total width and height needed
    CGFloat maxWidth = bounds.size.width - 4 * self.margin;
    CGSize totalSize = CGSizeZero;
    
    CGRect indicatorF = self.indicator.bounds;
    indicatorF.size.width = MIN(indicatorF.size.width, maxWidth);
    totalSize.width = MAX(totalSize.width, indicatorF.size.width);
    totalSize.height += indicatorF.size.height;
    
    CGSize labelSize = XY_TEXTSIZE(self.titleLabel.text, self.titleLabel.font);
    labelSize.width = MIN(labelSize.width, maxWidth);
    totalSize.width = MAX(totalSize.width, labelSize.width);
    totalSize.height += labelSize.height;
    if (labelSize.height > 0.f && indicatorF.size.height > 0.f) {
        totalSize.height += kPadding;
    }
    
    CGFloat remainingHeight = bounds.size.height - totalSize.height - kPadding - 4 * self.margin;
    CGSize maxSize = CGSizeMake(maxWidth, remainingHeight);
    CGSize detailsLabelSize = XY_MULTILINE_TEXTSIZE(self.detailLabel.text, self.detailLabel.font, maxSize, detailsLabel.lineBreakMode);
    if (self.attriDetailsLabelText) {
        detailsLabelSize.width = [self.attriDetailsLabelText boundingRectWithSize:CGSizeMake(0, detailsLabelSize.height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size.width+30;
    }
    totalSize.width = MAX(totalSize.width, detailsLabelSize.width);
    totalSize.height += detailsLabelSize.height;
    if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) {
        totalSize.height += kPadding;
    }
    
    totalSize.width += 2 * self.margin;
    totalSize.height += 2 * self.margin;
    
    
    // Position elements
    CGFloat top = 0;
    CGFloat bottomW = totalSize.width;
    if (self.isBlockUI) {
        top = round(((bounds.size.height - totalSize.height) / 2));
        bottomW = bounds.size.width;
    }
    CGFloat yPos = top + self.margin + self.yOffset;
    CGFloat xPos = self.xOffset;
    indicatorF.origin.y = yPos;
    indicatorF.origin.x = round((bottomW - indicatorF.size.width) / 2) + xPos;
    self.indicator.frame = indicatorF;
    yPos += indicatorF.size.height;
    
    if (labelSize.height > 0.f && indicatorF.size.height > 0.f) {
        yPos += kPadding;
    }
    CGRect labelF;
    labelF.origin.y = yPos;
    labelF.origin.x = round((bottomW - labelSize.width) / 2) + xPos;
    labelF.size = labelSize;
    self.titleLabel.frame = labelF;
    yPos += labelF.size.height;
    
    if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) {
        yPos += kPadding;
    }
    CGRect detailsLabelF;
    detailsLabelF.origin.y = yPos;
    detailsLabelF.origin.x = round((bottomW - detailsLabelSize.width) / 2) + xPos;
    detailsLabelF.size = detailsLabelSize;
    self.detailLabel.frame = detailsLabelF;
    
    // Enforce minsize and quare rules
    if (self.square) {
        CGFloat max = MAX(totalSize.width, totalSize.height);
        if (max <= bounds.size.width - 2 * self.margin) {
            totalSize.width = max;
        }
        if (max <= bounds.size.height - 2 * self.margin) {
            totalSize.height = max;
        }
    }
    if (totalSize.width < self.minSize.width) {
        totalSize.width = self.minSize.width;
    }
    if (totalSize.height < self.minSize.height) {
        totalSize.height = self.minSize.height;
    }
    
    self.size = totalSize;
    if (!self.isBlockUI) {
        bounds.size = totalSize;
        self.frame = bounds;
        self.center = CGPointMake(parent.bounds.size.width * 0.5, parent.bounds.size.height * 0.5);
    }
}
#pragma mark BG Drawing

- (void)drawRect:(CGRect)rect {
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    
    if (self.dimBackground) {
        //Gradient colours
        size_t gradLocationsNum = 2;
        CGFloat gradLocations[2] = {0.0f, 1.0f};
        CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.75f};
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);
        CGColorSpaceRelease(colorSpace);
        //Gradient center
        CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
        //Gradient radius
        float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;
        //Gradient draw
        CGContextDrawRadialGradient (context, gradient, gradCenter,
                                     0, gradCenter, gradRadius,
                                     kCGGradientDrawsAfterEndLocation);
        CGGradientRelease(gradient);
    }
    
    // Set background rect color
    if (self.color) {
        CGContextSetFillColorWithColor(context, self.color.CGColor);
    } else {
        CGContextSetGrayFillColor(context, 0.0f, self.opacity);
    }
    
    
    // Center HUD
    CGRect allRect = self.bounds;
    // Draw rounded HUD backgroud rect
    CGRect boxRect = CGRectMake(round((allRect.size.width - self.size.width) / 2) + self.xOffset,
                                round((allRect.size.height - self.size.height) / 2) + self.yOffset, self.size.width, self.size.height);
    float radius = self.cornerRadius;
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect));
    CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMinY(boxRect) + radius, radius, 3 * (float)M_PI / 2, 0, 0);
    CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMaxY(boxRect) - radius, radius, 0, (float)M_PI / 2, 0);
    CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMaxY(boxRect) - radius, radius, (float)M_PI / 2, (float)M_PI, 0);
    CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect) + radius, radius, (float)M_PI, 3 * (float)M_PI / 2, 0);
    CGContextClosePath(context);
    CGContextFillPath(context);
    
    UIGraphicsPopContext();
}
#pragma mark- private methods

-(void)_initDefaultValues{
    self.isBlockUI = YES;
    self.contentMode = UIViewContentModeCenter;
    self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    
    // Transparent background
    self.opaque = NO;
    self.backgroundColor = [UIColor clearColor];
    // Make it invisible for now
    self.alpha = 0.0f;
    
    rotationTransform = CGAffineTransformIdentity;
    
    self.animationType = XYProgressHUDAnimationFade;
    self.mode = XYProgressHUDModeIndeterminate;
    self.labelText = @"";
    self.detailsLabelText = @"";
    self.opacity = 0.7f;
    self.color = [UIColor colorWithHexString:@"#000000"];
    self.labelFont = [UIFont boldSystemFontOfSize:kLabelFontSize];
    self.labelColor = [UIColor whiteColor];
    self.detailsLabelFont = [UIFont boldSystemFontOfSize:kDetailsLabelFontSize];
    self.detailsLabelColor = [UIColor whiteColor];
    self.activityIndicatorColor = [UIColor whiteColor];
    self.xOffset = 0.0f;
    self.yOffset = 0.0f;
    self.dimBackground = NO;
    self.margin = 20.0f;
    self.cornerRadius = 6.0f;
    self.graceTime = 0.0f;
    self.minShowTime = 0.0f;
    self.removeFromSuperViewOnHide = NO;
    self.minSize = CGSizeZero;
    self.square = NO;
    self.taskInProgress = NO;
}
#pragma mark - View Hierrarchy

- (void)didMoveToSuperview {
    [self updateForCurrentOrientationAnimated:NO];
}

#pragma mark - Internal show & hide operations

- (void)showUsingAnimation:(BOOL)animated {
    // Cancel any scheduled hideDelayed: calls
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self setNeedsDisplay];
    
    if (animated && self.animationType == XYProgressHUDAnimationZoomIn) {
        self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f));
    } else if (animated && self.animationType == XYProgressHUDAnimationZoomOut) {
        self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f));
    }
    self.showStarted = [NSDate date];
    // Fade in
    if (animated) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.30];
        self.alpha = 1.0f;
        if (self.animationType == XYProgressHUDAnimationZoomIn || self.animationType == XYProgressHUDAnimationZoomOut) {
            self.transform = rotationTransform;
        }
        [UIView commitAnimations];
    }
    else {
        self.alpha = 1.0f;
    }
}

- (void)hideUsingAnimation:(BOOL)animated {
    // Fade out
    if (animated && self.showStarted) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.30];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
        // 0.02 prevents the hud from passing through touches during the animation the hud will get completely hidden
        // in the done method
        if (self.animationType == XYProgressHUDAnimationZoomIn) {
            self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f));
        } else if (self.animationType == XYProgressHUDAnimationZoomOut) {
            self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f));
        }
        
        self.alpha = 0.02f;
        [UIView commitAnimations];
    }
    else {
        self.alpha = 0.0f;
        [self done];
    }
    self.showStarted = nil;
}
- (void)animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void*)context {
    [self done];
}
- (void)done {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    isFinished = YES;
    self.alpha = 0.0f;
    if (self.removeFromSuperViewOnHide) {
        [self removeFromSuperview];
    }
#if NS_BLOCKS_AVAILABLE
    if (self.completionBlock) {
        self.completionBlock();
    }
#endif
}
#pragma mark - Show & hide

- (void)show:(BOOL)animated {
    NSAssert([NSThread isMainThread], @"MBProgressHUD needs to be accessed on the main thread.");
    useAnimation = animated;
    // If the grace time is set postpone the HUD display
    if (self.graceTime > 0.0) {
        NSTimer *newGraceTimer = [NSTimer timerWithTimeInterval:self.graceTime target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:newGraceTimer forMode:NSRunLoopCommonModes];
        self.graceTimer = newGraceTimer;
    }
    // ... otherwise show the HUD imediately
    else {
        [self showUsingAnimation:useAnimation];
    }
}

- (void)hide:(BOOL)animated {
    NSAssert([NSThread isMainThread], @"MBProgressHUD needs to be accessed on the main thread.");
    useAnimation = animated;
    // If the minShow time is set, calculate how long the hud was shown,
    // and pospone the hiding operation if necessary
    if (self.minShowTime > 0.0 && self.showStarted) {
        NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:self.showStarted];
        if (interv < self.minShowTime) {
            self.minShowTimer = [NSTimer scheduledTimerWithTimeInterval:(self.minShowTime - interv) target:self
                                                               selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO];
            return;
        }
    }
    // ... otherwise hide the HUD immediately
    [self hideUsingAnimation:useAnimation];
}

- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay {
    [self performSelector:@selector(hideDelayed:) withObject:[NSNumber numberWithBool:animated] afterDelay:delay];
}

- (void)hideDelayed:(NSNumber *)animated {
    [self hide:[animated boolValue]];
}

#pragma mark - Timer callbacks

- (void)handleGraceTimer:(NSTimer *)theTimer {
    // Show the HUD only if the task is still running
    if (self.taskInProgress) {
        [self showUsingAnimation:useAnimation];
    }
}

- (void)handleMinShowTimer:(NSTimer *)theTimer {
    [self hideUsingAnimation:useAnimation];
}
#pragma mark - UI

- (void)_setupLabels {
    self.titleLabel = [[UILabel alloc] initWithFrame:self.bounds];
    self.titleLabel.adjustsFontSizeToFitWidth = NO;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.opaque = NO;
    self.titleLabel.backgroundColor = [UIColor clearColor];
    self.titleLabel.textColor = self.labelColor;
    self.titleLabel.font = self.labelFont;
    self.titleLabel.text = self.labelText;
    [self addSubview:self.titleLabel];
    
    self.detailLabel = [[UILabel alloc] initWithFrame:self.bounds];
    self.detailLabel.font = self.detailsLabelFont;
    self.detailLabel.adjustsFontSizeToFitWidth = NO;
    self.detailLabel.textAlignment = NSTextAlignmentCenter;
    self.detailLabel.opaque = NO;
    self.detailLabel.backgroundColor = [UIColor clearColor];
    self.detailLabel.textColor = self.detailsLabelColor;
    self.detailLabel.numberOfLines = 0;
    self.detailLabel.font = self.detailsLabelFont;
    if (self.attriDetailsLabelText) {
        self.detailLabel.attributedText = self.attriDetailsLabelText;
    }else {
        self.detailLabel.text = self.detailsLabelText;
    }
    [self addSubview:self.detailLabel];
}

- (void)_updateIndicators {
    
    BOOL isActivityIndicator = [self.indicator isKindOfClass:[UIActivityIndicatorView class]];
//    BOOL isRoundIndicator = [self.indicator isKindOfClass:[MBRoundProgressView class]];
    
    if (self.mode == XYProgressHUDModeIndeterminate) {
        if (!isActivityIndicator) {
            // Update to indeterminate indicator
            [self.indicator removeFromSuperview];
            self.indicator = [[UIActivityIndicatorView alloc]
                              initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
            [(UIActivityIndicatorView *)self.indicator startAnimating];
            [self addSubview:self.indicator];
        }
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000
        [(UIActivityIndicatorView *)self.indicator setColor:self.activityIndicatorColor];
#endif
    }
//    else if (self.mode == XYProgressHUDModeDeterminateHorizontalBar) {
//        // Update to bar determinate indicator
//        [indicator removeFromSuperview];
//        self.indicator = MB_AUTORELEASE([[MBBarProgressView alloc] init]);
//        [self addSubview:indicator];
//    }
//    else if (self.mode == XYProgressHUDModeDeterminate || self.mode == XYProgressHUDModeAnnularDeterminate) {
//        if (!isRoundIndicator) {
//            // Update to determinante indicator
//            [self.indicator removeFromSuperview];
//            self.indicator = MB_AUTORELEASE([[MBRoundProgressView alloc] init]);
//            [self addSubview:indicator];
//        }
//        if (self.mode == XYProgressHUDModeAnnularDeterminate) {
//            [(MBRoundProgressView *)indicator setAnnular:YES];
//        }
//        [(MBRoundProgressView *)indicator setProgressTintColor:self.activityIndicatorColor];
//        [(MBRoundProgressView *)indicator setBackgroundTintColor:[self.activityIndicatorColor colorWithAlphaComponent:0.1f]];
//    }
    else if (self.mode == XYProgressHUDModeCustomView && self.customView != self.indicator) {
        // Update custom view indicator
        [self.indicator removeFromSuperview];
        self.indicator = self.customView;
        [self addSubview:self.indicator];
    } else if (self.mode == XYProgressHUDModeText) {
        [self.indicator removeFromSuperview];
        self.indicator = nil;
    }
}

#pragma mark - KVO

- (void)_registerForKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
    }
}

- (void)_unregisterFromKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [self removeObserver:self forKeyPath:keyPath];
    }
}

- (NSArray *)observableKeypaths {
    return [NSArray arrayWithObjects:@"mode", @"customView", @"labelText", @"labelFont", @"labelColor",
            @"detailsLabelText", @"attriDetailsLabelText", @"detailsLabelFont", @"detailsLabelColor", @"progress", @"activityIndicatorColor", nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(_updateUIForKeypath:) withObject:keyPath waitUntilDone:NO];
    } else {
        [self _updateUIForKeypath:keyPath];
    }
}

- (void)_updateUIForKeypath:(NSString *)keyPath {
    if ([keyPath isEqualToString:@"mode"] || [keyPath isEqualToString:@"customView"] ||
        [keyPath isEqualToString:@"activityIndicatorColor"]) {
        [self _updateIndicators];
    } else if ([keyPath isEqualToString:@"labelText"]) {
        self.titleLabel.text = self.labelText;
    } else if ([keyPath isEqualToString:@"labelFont"]) {
        self.titleLabel.font = self.labelFont;
    } else if ([keyPath isEqualToString:@"labelColor"]) {
        self.titleLabel.textColor = self.labelColor;
    } else if ([keyPath isEqualToString:@"detailsLabelText"]) {
        self.detailLabel.text = self.detailsLabelText;
    } else if ([keyPath isEqualToString:@"attriDetailsLabelText"]) {
        self.detailLabel.attributedText = self.attriDetailsLabelText;
    } else if ([keyPath isEqualToString:@"detailsLabelFont"]) {
        self.detailLabel.font = self.detailsLabelFont;
    } else if ([keyPath isEqualToString:@"detailsLabelColor"]) {
        self.detailLabel.textColor = self.detailsLabelColor;
    } else if ([keyPath isEqualToString:@"progress"]) {
        if ([self.indicator respondsToSelector:@selector(setProgress:)]) {
            [(id)self.indicator setValue:@(self.progress) forKey:@"progress"];
        }
        return;
    }
    [self setNeedsLayout];
    [self setNeedsDisplay];
}
#pragma mark - Notifications

- (void)_registerForNotifications {
#if !TARGET_OS_TV
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    
    [nc addObserver:self selector:@selector(statusBarOrientationDidChange:)
               name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
#endif
}

- (void)_unregisterFromNotifications {
#if !TARGET_OS_TV
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
#endif
}

#if !TARGET_OS_TV
- (void)statusBarOrientationDidChange:(NSNotification *)notification {
    UIView *superview = self.superview;
    if (!superview) {
        return;
    } else {
        [self updateForCurrentOrientationAnimated:YES];
    }
}
#endif

- (void)updateForCurrentOrientationAnimated:(BOOL)animated {
    // Stay in sync with the superview in any case
    if (self.superview) {
        self.bounds = self.superview.bounds;
        [self setNeedsDisplay];
    }
    
    // Not needed on iOS 8+, compile out when the deployment target allows,
    // to avoid sharedApplication problems on extension targets
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000
    // Only needed pre iOS 7 when added to a window
    BOOL iOS8OrLater = kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0;
    if (iOS8OrLater || ![self.superview isKindOfClass:[UIWindow class]]) return;
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    CGFloat radians = 0;
    if (UIInterfaceOrientationIsLandscape(orientation)) {
        if (orientation == UIInterfaceOrientationLandscapeLeft) { radians = -(CGFloat)M_PI_2; }
        else { radians = (CGFloat)M_PI_2; }
        // Window coordinates differ!
        self.bounds = CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.width);
    } else {
        if (orientation == UIInterfaceOrientationPortraitUpsideDown) { radians = (CGFloat)M_PI; }
        else { radians = 0; }
    }
    rotationTransform = CGAffineTransformMakeRotation(radians);
    
    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
    }
    [self setTransform:rotationTransform];
    if (animated) {
        [UIView commitAnimations];
    }
#endif
}
@end
